#!/bin/bash
# 用于处理自动build后加密问题（仅173需要执行）
# 在 Git Bash 中调用 PowerShell 命令
echo "使用 PowerShell 监听 dist 目录..."
echo "全局命令: jie.sh"
echo "执行目录: ./dist"
echo "开始时间: $(date)"
echo "按 Ctrl+C 停止监听"
echo "----------------------------------------"

# 执行 PowerShell 监听命令
powershell -Command "
# 设置监听路径
\$watchPath = (Resolve-Path './dist').Path
\$scriptToRun = 'jie.sh'

Write-Host '🔍 监听目录: ' \$watchPath
Write-Host '🏃 执行命令: ' \$scriptToRun
Write-Host '⏰ 开始时间: ' (Get-Date)

# 检查目录是否存在
if (-not (Test-Path \$watchPath -PathType Container)) {
    Write-Host '❌ 错误: dist 目录不存在' -ForegroundColor Red
    exit 1
}

# 创建文件监视器
\$watcher = New-Object System.IO.FileSystemWatcher
\$watcher.Path = \$watchPath
\$watcher.IncludeSubdirectories = \$true
\$watcher.EnableRaisingEvents = \$true
\$watcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite

# 避免快速连续触发
\$lastEventTime = Get-Date
\$debounceInterval = New-TimeSpan -Seconds 3

\$action = {
    param(\$source, \$e)

    # 防抖处理：3秒内不重复触发
    \$currentTime = Get-Date
    if ((\$currentTime - \$lastEventTime) -lt \$debounceInterval) {
        return
    }
    \$lastEventTime = \$currentTime
    
    # 排除临时文件
    if (\$e.Name -match '\.tmp\$|\.swp\$|~\$|\.log\$') {
        return
    }
    
    Write-Host '📁 文件变化: ' \$e.FullPath -ForegroundColor Cyan
    Write-Host '🕒 变化时间: ' (Get-Date) -ForegroundColor Yellow
    
    # 保存当前目录
    \$originalDir = Get-Location
    
    try {
        # 切换到 dist 目录执行
        Set-Location \$watchPath
        Write-Host '📂 切换到目录: ' (Get-Location) -ForegroundColor Green
        
        # 执行全局命令 jie.sh
        if (Get-Command \$scriptToRun -ErrorAction SilentlyContinue) {
            Write-Host '🏃 执行命令: ' \$scriptToRun -ForegroundColor Green
            bash -c \"\$scriptToRun\"
            if (\$LASTEXITCODE -eq 0) {
                Write-Host '✅ 命令执行完成' -ForegroundColor Green
            } else {
                Write-Host '❌ 命令执行失败，退出码: ' \$LASTEXITCODE -ForegroundColor Red
            }
        } else {
            Write-Host '❌ 命令未找到: ' \$scriptToRun -ForegroundColor Red
            Write-Host '💡 请确保 jie.sh 在系统 PATH 中' -ForegroundColor Yellow
        }
    }
    catch {
        Write-Host '❌ 执行错误: ' \$_.Exception.Message -ForegroundColor Red
    }
    finally {
        # 返回原目录
        Set-Location \$originalDir
        Write-Host '↩️  返回目录: ' (Get-Location) -ForegroundColor Gray
    }
    
    Write-Host '----------------------------------------' -ForegroundColor Gray
}

# 注册事件
\$event = Register-ObjectEvent \$watcher 'Changed' -Action \$action

Write-Host '🎯 开始监听... (按 Ctrl+C 停止)' -ForegroundColor Green

try {
    # 保持运行
    while (\$true) { 
        Start-Sleep -Seconds 1 
    }
}
finally {
    Write-Host '🛑 停止监听' -ForegroundColor Yellow
    # 清理资源
    \$watcher.EnableRaisingEvents = \$false
    \$event | Unregister-Event
    \$watcher.Dispose()
    \$event | Remove-Job
}
"